package cn.kuang.service;

import cn.kuang.mapper.CategoryMapper;
import cn.kuang.mapper.RouteImgMapper;
import cn.kuang.mapper.RouteMapper;
import cn.kuang.mapper.SellerMapper;
import cn.kuang.pojo.Category;
import cn.kuang.pojo.Route;
import cn.kuang.pojo.RouteImg;
import cn.kuang.pojo.Seller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 徽州大都督
 * @date 2020/7/27
 */
@Service
@Transactional
public class RouteService {

    @Autowired
    private RouteMapper routeMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RouteImgMapper routeImgMapper;

    @Autowired
    private SellerMapper sellerMapper;

    public List<Route> findPage(Integer page, Integer size, Integer cid) {

        if (redisTemplate.opsForHash ().entries ("pageList") != null) {
            Map map = redisTemplate.opsForHash ().entries ("pageList");

            if (map.containsKey (page.toString ())) {

                //System.out.println ("缓存中查询...");
                Object o = map.get (page.toString ());
                return (List<Route>) o;


            } else {
                Page<Route> page1 = new Page<> (page, size);
                QueryWrapper<Route> wrapper = new QueryWrapper<> ();
                wrapper.eq ("cid", cid);
                routeMapper.selectPage (page1, wrapper);

                List<Route> routeList = page1.getRecords ();
                routeList.forEach (route -> {
                    Category category = categoryMapper.selectById (route.getCid ());
                    route.setCategory (category);
                    route.setTotal (page1.getTotal ());
                });

                map.put (page.toString (), routeList);
                redisTemplate.opsForHash ().putAll ("pageList", map);

                //System.out.println ("数据库中查询");
                return routeList;
            }

        } else {
            Page<Route> page1 = new Page<> (page, size);
            QueryWrapper<Route> wrapper = new QueryWrapper<> ();
            wrapper.eq ("cid", cid);
            routeMapper.selectPage (page1, wrapper);

            List<Route> routeList = page1.getRecords ();
            routeList.forEach (route -> {
                Category category = categoryMapper.selectById (route.getCid ());
                route.setCategory (category);
                route.setTotal (page1.getTotal ());
            });

            Map map = new HashMap ();
            map.put (page.toString (), routeList);
            redisTemplate.opsForHash ().putAll ("pageList", map);

            //System.out.println ("数据库中查询，存入缓存...");
            return routeList;
        }


    }


    public Route findByRid(Integer rid) {
        Route route = routeMapper.selectById (rid);

        QueryWrapper<RouteImg> wrapper = new QueryWrapper<> ();
        wrapper.eq ("rid", rid);
        List<RouteImg> routeImgList = routeImgMapper.selectList (wrapper);
        route.setRouteImgs (routeImgList);

        Category category = categoryMapper.selectById (route.getCid ());
        route.setCategory (category);
        Seller seller = sellerMapper.selectById (route.getSid ());
        route.setSeller (seller);

        return route;
    }

    /**
     * 用户收藏
     *
     * @param username
     * @param rid
     */
    public String collection(String username, Integer rid) {

        Route route = routeMapper.selectById (rid);
        if (redisTemplate.opsForValue ().get (username) == null) {
            List<Route> routeList = new ArrayList<> ();
            routeList.add (route);

            redisTemplate.opsForValue ().set (username, routeList, 30, TimeUnit.MINUTES);

            //System.out.println ("缓存中不存在，创建并添加成功");

            return "success";
        } else {
            List<Route> routeList = (List<Route>) redisTemplate.opsForValue ().get (username);
            if (!routeList.contains (route)) {
                routeList.add (route);
                redisTemplate.opsForValue ().set (username, routeList, 30, TimeUnit.MINUTES);

                // System.out.println ("缓存中存在，创建并添加成功");

                return "success";
            } else {
                //System.out.println ("缓存中已经存在，添加失败");

                return "error";
            }
        }
    }

    public List<Route> findByPage(Integer page, Integer size, String username) {

        if (redisTemplate.opsForValue ().get (username) != null) {

            List<Route> routeList = (List<Route>) redisTemplate.opsForValue ().get (username);
            List<List<Route>> partition = ListUtils.partition (routeList, size);
            List<Route> routeList1 = partition.get (page - 1);

            for (Route route : routeList1) {
                route.setTotal ((long) routeList.size ());
            }
            return routeList1;

        } else {

            List<Route> routes = new ArrayList<> ();
            return routes;
        }


    }


    public List<Route> findByRname(Integer page, Integer size, String rname) {
        Page<Route> page1 = new Page<> (page,size);

        QueryWrapper<Route> wrapper = new QueryWrapper<> ();
        wrapper.like ("rname",rname);
        routeMapper.selectPage (page1,wrapper);
        List<Route> routeList = page1.getRecords ();
        long total = page1.getTotal ();

        if (!CollectionUtils.isEmpty (routeList)){
            routeList.forEach (route -> {
                route.setTotal (total);
            });
        }
        return routeList;
    }
}
